package top.oneit.jdownload.data.dao;

import org.hibernate.Session;
import top.oneit.jdownload.JdownloadApplication;

import java.io.Serializable;
import java.util.List;

/**
 * @author lingkang
 * @date 2021/11/21
 */
public class BaseDao {
    protected static Session getSession() {
        return JdownloadApplication.sessionFactory.getCurrentSession();
    }

    public static void save(Object o) {
        Session session = getSession();
        session.beginTransaction();
        session.save(o);
        session.getTransaction().commit();
    }

    public static void save(Object... os) {
        Session session = getSession();
        session.beginTransaction();
        for (Object o : os) {
            session.save(o);
        }
        session.getTransaction().commit();
    }

    public static void save(List ls) {
        Session session = getSession();
        session.beginTransaction();
        for (int i = 0; i < ls.size(); i++)
            session.save(ls.get(i));
        session.getTransaction().commit();
    }

    public static void update(Object o) {
        Session session = getSession();
        session.beginTransaction();
        session.update(o);
        session.getTransaction().commit();
    }

    public static void delete(Object o){
        Session session = getSession();
        session.beginTransaction();
        session.delete(o);
        session.getTransaction().commit();
    }

    public static <T> void update(List<T> ls) {
        Session session = getSession();
        session.beginTransaction();
        for (Object o : ls) {
            session.update((T) o);
        }
        session.getTransaction().commit();
    }

    public static <T> T get(Class<T> clazz, Serializable id) {
        Session session = getSession();
        session.beginTransaction();
        T t = session.get(clazz, id);
        session.getTransaction().commit();
        return t;
    }

    public static <T> List<T> getList(Class<T> clazz) {
        Session session = getSession();
        session.beginTransaction();
        List<T> list = session.createQuery("from " + clazz.getSimpleName()).list();
        session.getTransaction().commit();
        return list;
    }

}
